package com.accp.ssmoa.controller;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.accp.ssmoa.pojo.ActivitiModel;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

@Controller
@Scope("prototype")
@RequestMapping("/admin/model")
public class ModelController {

	// 获取仓库服务对象
    @Autowired  
    private RepositoryService repositoryService;


	//实现添加
	@RequestMapping(value="/doSave",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Boolean> doSave(@ModelAttribute("ActivitiModel") ActivitiModel model,
			HttpServletResponse response,HttpServletRequest request) {
		
		Map<String,Boolean> result=new HashMap<String, Boolean>();
		
	    try {
	    	
	    		ObjectMapper objectMapper = new ObjectMapper();
	            ObjectNode editorNode = objectMapper.createObjectNode();
	            editorNode.put("id", "canvas");
	            editorNode.put("resourceId", "canvas");
	            ObjectNode stencilSetNode = objectMapper.createObjectNode();
	            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
	            
	            
	            editorNode.put("stencilset", stencilSetNode);
	           
	            
	            Model modelData = repositoryService.newModel();

	            ObjectNode modelObjectNode = objectMapper.createObjectNode();
	            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
	            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION,model.getVersion());
	            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, model.getDescription());
	            
	            
	            
	            modelData.setMetaInfo(modelObjectNode.toString());
	            modelData.setName(model.getName());
	            modelData.setKey(model.getKey());

	            //保存模型
	            repositoryService.saveModel(modelData);
	            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
	            	    	

	    	
/*	        ObjectMapper objectMapper = new ObjectMapper();
	        ObjectNode editorNode = objectMapper.createObjectNode();
	        editorNode.put("id", "canvas");
	        editorNode.put("resourceId", "canvas");
	        ObjectNode stencilSetNode = objectMapper.createObjectNode();
	        stencilSetNode.put("namespace", "https://b3mn.org/stencilset/bpmn2.0#");
	        
	        
	        editorNode.put("stencilset", stencilSetNode);*/
	        
	        
	        //实例化出repositoryService提供的实体类
	       // Model modelData = repositoryService.newModel();
	        
	        //存储信息到model的MetaInfo字段
	       // ObjectNode modelObjectNode = objectMapper.createObjectNode();
	        //modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, model.getName());
	       // modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION,model.getVersion());
	        //String description = StringUtils.defaultString(model.getDescription());
	       // modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, model.getDescription());

	        //将信息存进实体类
	        //modelData.setMetaInfo(modelObjectNode.toString());
	        //modelData.setName(model.getName());
	        //modelData.setKey(model.getKey());

	        //使用repositoryService进行保存持久化操作哦
	        //repositoryService.saveModel(modelData);
	        //repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
	        
	    } catch (Exception e) {
	       System.out.println("创建模型失败");
	    }		
	    
	    result.put("success", true);
	    
	    return result;
		
	}    
    
    
	// 分页显示模型信息
	@RequestMapping(value = "/listData", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map<String, Object> listData(@RequestBody JSONObject jsonObj) {

		// 取出前台传过来的封装在json格式里面的数据
		Integer pageSize = jsonObj.getIntValue("pageSize"); // 每页显示数据条数
		Integer startRow = jsonObj.getIntValue("startRow"); // 当前页码

		// 总数据数		
		int totalsize = (int) repositoryService.createModelQuery().count();
		Map<String, Object> map = new HashMap<String, Object>();

		List<Model> list = repositoryService.createModelQuery().listPage(startRow, pageSize);
		
		List<ActivitiModel> resultList=new ArrayList<ActivitiModel>();
		
		for (Model model : list) {
			ActivitiModel model2=new ActivitiModel();
			model2.setId(model.getId());
			model2.setKey(model.getKey());
			model2.setName(model.getName());
			model2.setVersion(model.getVersion());
			model2.setCreateTime(model.getCreateTime());
			model2.setLastUpdateTime(model.getLastUpdateTime());

			resultList.add(model2);
		}

		// total表示数据总数，rows表示需要显示的数据。必须按照这种格式返回才行。
		map.put("total", totalsize);
		map.put("rows", resultList);

		return map;
	}
    
    
    
    
    
	
	/*需要权限控制的操作*/
    
    
	//初始化模型信息页面
	@RequestMapping("/getListPage")
	public String getListPage(HttpServletRequest request) {

		//存储面包屑导航的值进request作用域
		request.setAttribute("pageTitle","模型管理");
		
		request.setAttribute("url","/admin/model/getListPage");
		
		request.setAttribute("nowBread","管理");
		
		
		return "workflow/model/list";
	}
	
	
	
	//提供添加模型信息页面
	@RequestMapping("/save")
	public String save(HttpServletRequest request) {

		
		//存储面包屑导航的值进request作用域
		request.setAttribute("pageTitle","模型管理");
		request.setAttribute("url","/admin/model/getListPage");	
		request.setAttribute("nowBread","添加新模型");

		return "workflow/model/add";
	}
	

	// 实现删除
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(@RequestParam(value = "idsArr[]") String[] idsAttr) {

		Map<String, Object> result = new HashMap<String, Object>();

		for (String idString : idsAttr) {

			repositoryService.deleteModel(idString);
		}


		result.put("success", true);
		result.put("message", "删除成功");


		return result;

	}


	//实现部署
	@RequestMapping(value = "deploy",method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deploy(@RequestParam("id") String modelId, HttpServletRequest request) {
	   
		
		Map<String, Object> result=new HashMap<String, Object>();
		try {
			
			Model modelData = repositoryService.getModel(modelId);
			BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
			JsonNode editorNode = new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
			BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
			BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
			byte[] bpmnBytes = xmlConverter.convertToXML(bpmnModel,"ISO-8859-1");
			
			String processName = modelData.getName();
			if (!StringUtils.endsWith(processName, ".bpmn20.xml")){
				processName += ".bpmn20.xml";
			}
//			System.out.println("========="+processName+"============"+modelData.getName());
			ByteArrayInputStream in = new ByteArrayInputStream(bpmnBytes);
			Deployment deployment = repositoryService.createDeployment().name(modelData.getName())
					.addInputStream(processName, in).deploy();
//					.addString(processName, new String(bpmnBytes)).deploy();
			
			// 设置流程分类
			List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list();
			for (ProcessDefinition processDefinition : list) {
				repositoryService.setProcessDefinitionCategory(processDefinition.getId(), modelData.getCategory());
		        result.put("message", "部署成功");
		        result.put("type", "success");
			}
			if (list.size() == 0){
		        result.put("message", "部署失败,没有流程");
		        result.put("type", "danger");
			}
		} catch (Exception e) {
			throw new ActivitiException("设计模型图不正确，检查模型正确性", e);
		}
	    
	    return result;
	}

}
